package com.rykj.qxj.server.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

public class DES {

	//private String KEY = "Wcqk@ETL123";
	private String KEY = "HpgYZN6y$krTKcumKotSl%wzDAB3tSc1";
    private String CODE_TYPE = "UTF-8";

	public static void main(String[] args) throws Exception {
		//DES des = new DES("Wcqk@ETL123");
		//System.out.println(des.encode("123456"));
	    // System.out.println(des.decode("hWJZMMbNkLI="));

	}

	/**
	 * 使用默认key： Wcqk@ETL123
	 */
	public DES() {

	}

	public DES(String key) {
		KEY = key;
	}

	public DES(String key, String charset) {
		KEY = key;
		CODE_TYPE = charset;
	}

	/**
	 * DES加密
	 * @param datasource
	 * @return
	 */
	public String encode(String datasource){
		if(StringUtils.isBlank(datasource)) return null;
	    try{
	        SecureRandom random = new SecureRandom();
	        DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE));
	        //创建一个密匙工厂，然后用它把DESKeySpec转换成
	        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	        SecretKey securekey = keyFactory.generateSecret(desKey);
	        //Cipher对象实际完成加密操作
	        Cipher cipher = Cipher.getInstance("DES");
	        //用密匙初始化Cipher对象
	        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
	        //现在，获取数据并加密
	        byte[] temp = Base64.encodeBase64(cipher.doFinal(datasource.getBytes()));
	        return IOUtils.toString(temp, CODE_TYPE);
	    }catch(Throwable e){
	        e.printStackTrace();
	        return null;
	    }
	}

	/**
	 * DES解密
	 * @return
	 */
	public String decode(String src){
		if(StringUtils.isBlank(src)) return null;
		try {
			// DES算法要求有一个可信任的随机数源
			SecureRandom random = new SecureRandom();
			// 创建一个DESKeySpec对象
			DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE));
			// 创建一个密匙工厂
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// 将DESKeySpec对象转换成SecretKey对象
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance("DES");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, random);
			// 真正开始解密操作
			return IOUtils.toString(cipher.doFinal(Base64.decodeBase64(src)), CODE_TYPE);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
